package com.ww.utils;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * 类处理类
 * @author wangwei
 *
 */
public class ClassUtil {
	
	/**
	 * 将Class中String字段的前后空格去掉
	 * @param c
	 * 		类型Class<?>
	 * @param obj
	 * 		需要处理的对象
	 */
	public static void strTrimByClass(Class<?> c, Object obj){
		Field[] fields = c.getDeclaredFields();
		for (Field field : fields) {
			if(field.getType() == String.class){
				field.setAccessible(true);
				try {
					if(field.get(obj) != null){
						String tmp = (String) field.get(obj);
						field.set(obj, tmp.trim());
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 参数转为 encode url
	 * @param c
	 * @param obj
	 * @return
	 */
	public static String encodeParam(Class<?> c, Object obj){
		String url = "";
		Field[] fields = c.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				if(field.getType() == String.class){
					if(field.get(obj) != null){
						String val = (String) field.get(obj);
						url += "&" + field.getName() + "=" + val;
					}
				}else if(field.getType() == Date.class){
					if(field.get(obj) != null){
						String val = DateUtils.formatDate((Date)field.get(obj), null);
						url += "&" + field.getName() + "=" + val;
					}
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		url = url.replaceFirst("&", "?");
		return url;
	}
	
	
	
	public static void main(String[] args) {
//		PriceQueryParam entity = new PriceQueryParam();
//		entity.setPid("123");
//		entity.setPricename("aaaaa");
//		entity.setStartdate(new Date());
//		System.out.println(ClassUtil.encodeParam(PriceQueryParam.class, entity));
	}
}
